﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Xml.Linq;

namespace RPGXEngine.Object
{
    public static class ModelPool
    {
        #region Properties

        public static Dictionary<string, GameMeshModel> Models
        {
            get { return ModelPool._models; }
        }
        private static Dictionary<string, GameMeshModel> _models = new Dictionary<string, GameMeshModel>();

        public static List<GameMesh> SharedModels
        {
            get { return _sharedModels; }
            set { _sharedModels = value; }
        }
        private static List<GameMesh> _sharedModels = new List<GameMesh>();

        #endregion

        #region Public Static Methods

        public static void FromXML(string filename)
        {
            XDocument doc = XDocument.Load(filename);

            var meshes = doc.Element("models").Elements("gamemesh");

            foreach (var mesh in meshes)
            {
                GameMesh m = new GameMesh();
                m.FromXML(mesh);

                ModelPool.SharedModels.Add(m);
            }
        }

        public static GameMeshModel Add(string assetName, ContentManager content)
        {
            GameMeshModel model = null;

            assetName = assetName.ToLower().Trim();

            if (ModelPool.Models.ContainsKey(assetName))
            {
                model = ModelPool.Models[assetName];
            }
            else
            {
                model = new GameMeshModel();

                foreach (GameMesh mesh in ModelPool.SharedModels)
                {
                    if (mesh.FileName == assetName)
                    {
                        model = mesh.RenderModel;
                    }
                }

                model.Model = content.Load<Model>(assetName);
                ModelPool.Models.Add(assetName, model);

                ModelPool.SetupModelTextures(model);
            }

            return model;
        }

        #endregion

        #region Private Static Methods

        private static void SetupModelTextures(GameMeshModel model)
        {
            List<Texture2D> textures = new List<Texture2D>();

            foreach (ModelMesh modelMesh in model.Model.Meshes)
            {
                foreach (BasicEffect fx in modelMesh.Effects)
                {
                    textures.Add(fx.Texture);
                }
            }

            model.Textures = textures.ToArray();
        }

        #endregion
    }
}
